package oneplay.YonghongBITools.BatchDownload;

import lombok.extern.slf4j.Slf4j;
import oneplay.YonghongBITools.YHWebAPI;
import oneplay.YonghongBITools.utils.PropertiesUtil;
import oneplay.YonghongBITools.utils.StandPrint;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class Main {

    public static void main(String[] args) {
        if (args.length < 3) {
            System.out.println("Usage: username password dataInFormatJSON");
            System.exit(1);
        }
        YHWebAPI yhWebAPI = new YHWebAPI(PropertiesUtil.getProperty("YH_URL_API"));
        try {
            yhWebAPI.login(args[0], args[1]);
            BatchDownloadConfig batchDownloadConfig = new BatchDownloadConfig(new File(args[2]));
            boolean landscape = batchDownloadConfig.isLandscape();
            Short fitWidth = batchDownloadConfig.getFitWidth();
            Short fitHeight = batchDownloadConfig.getFitHeight();
            String pathOfBI = batchDownloadConfig.getPath();
            String filename = batchDownloadConfig.getName();
            Path pathOfZipFile = Paths.get(filename + ".zip");
            try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(pathOfZipFile))) {
                int counter = 1;
                for (Map<String, String> params : batchDownloadConfig.getBatchParams()) {
                    String entry = String.format("%d-%s.xlsx", counter, params.getOrDefault("_EXCEL_EXPORT_SHEETNAME_", filename));
                    log.info(entry);
                    zipOutputStream.putNextEntry(new ZipEntry(entry));
                    try (ByteArrayOutputStream xlsx = new ByteArrayOutputStream()) {
                        byte[] yhBytes = yhWebAPI.downloadFile(pathOfBI, params);
                        StandPrint.write(yhBytes, landscape, fitWidth, fitHeight, xlsx);
                        IOUtils.write(xlsx.toByteArray(), zipOutputStream);
                        zipOutputStream.flush();
                    }
                    counter++;
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            yhWebAPI.logout();
        }
    }

}
